var WechatAPI = require('co-wechat-api');
var util = require('../utils/util');

module.exports = {
    initApp: function (singleAccModel) {
        var isExchangeToken = (!singleAccModel.access_token) || (!singleAccModel.expire_time);
        isExchangeToken = util.isExpired(singleAccModel.expire_time);
        // Token是否在有效期内
        // 如果没有则更换
        var api = new WechatAPI(singleAccModel.app_id, singleAccModel.app_secret, async function () {
            return singleAccModel.access_token;
        }, async function (token) {
            singleAccModel.access_token = token.accessToken;
            singleAccModel.expire_time = token.expireTime;
            singleAccModel.save();
        });
        if (isExchangeToken) {
            api.getAccessToken();
        }
        return api;
    },
    replyHandler: function (_do, app_id, touser, key, api, dbmodel) {
        dbmodel.find({
            where: {
                and: [{
                    app_id: app_id
                }, {
                    key: key
                }, {
                    do: _do
                }]
            }
        }, function (err, replys) {
            if (err || replys.length <= 0)
                return api.sendText(touser, "～对不起，我们还没有想好这个" + key + "怎么做...");
            for (var i in replys) {
                switch (replys[i].type) {
                    case "text":
                        api.sendText(touser, replys[i].content);
                        break;
                    case "image":
                        api.sendImage(touser, replys[i].content);
                        break;
                    case "voice":
                        api.sendVoice(touser, replys[i].content);
                        break;
                    case "card":
                        api.sendCard(touser, replys[i].content);
                        break;
                    case "video":
                        api.sendVideo(touser, replys[i].content);
                        break;
                    case "music":
                        var music = JSON.parse(replys[i].content);
                        api.sendMusic(touser, music);
                        break;
                    case "news":
                        var articles = JSON.parse(replys[i].content);
                        api.sendNews(touser, articles);
                        break;
                    default:
                        // pass
                        continue;
                }
            }
        })
    }
}